﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using CommDll;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace InstitutionAssitant
{
    /// <summary>
    /// ClassName:frmPlatformOrder
    /// Version:1.0
    /// Date:2019-06-04
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为本地配送辅助入库处理
    /// </remarks>
    public partial class frmDeliveryToStockIn : DevComponents.DotNetBar.OfficeForm
    {
        #region 01.自定义属性
        int m_nFieldSelectedOrder = 1;  // 选择列所在顺序位置(0为起始列)
        public Boolean m_bIsSelectBegin = false;    //多选时用

        public string[] m_cbbData;  // 保存配送企业信息,过滤信息用
        public string[] m_cbbData1;  // 保存扫码人信息,过滤信息用
        public DataTable m_dt;  // 保存查询出来的数据
        private string m_strSql;    // 查询语句
        #endregion
        public frmDeliveryToStockIn()
        {
            InitializeComponent();
        }
        #region 02.自定义方法

        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strInfo = "";
            string strKind = "";
            // 01 frmLocalOrder
            strKind = this.Name;
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,Code-药品编码,Code_His-药品编码HIS,Name-药品名称,Name_His-药品名称HIS,Spec-规格,Manufacturer-生产厂家,Price-单价,WarehouseAmount-入库数,Money-金额,DeliveryCode-配送单号,DeliveryDetailCode-配送细单号,SupplierCode-配企编号,SupplierName-配企名称,SupplierCode_His-配企编号HIS,SupplierName_His-配企名称HIS,DeliveryTime-配送时间,"
                + "Spec_His-规格HIS,Manufacturer_His-生产厂家HIS,RegistrationCode-批准文号,RegistrationCode_His-批准文号HIS,Form-剂型,Form_His-剂型HIS,UnitMinForm-规格单位"
                + ",BatchCode-生产批号,MakeDate-生产日期,ExpiredDate-生效日期,Unit-单位,Unit_His-单位HIS,UnitRatio-单位包装比,WarehouseRatio-转换率,Price_His-单价HIS,Price_Warehouse-入库价,Amount-数量,PurchaseAmount-采购数量,InvoiceNo-发票号,InvoiceDate-发票日期,Salesman-业务员"
                + ",StockInStatus-入库状态,StockInTime-入库时间,WarehouseCode-药库编号,WarehouseName-药库名称,PurchaseOrderCode-采购单号,PurchaseOrderDetailCode-采购细单号,PurchaseTime-采购时间,StockInId-入库单号,InvoiceCheckStatus-发票核对状态,SupervisionCodeStatus-溯源码状态,ReciveStatus-收货状态,TwoTicksStatus-两票凭证状态,OperateUserName-扫码人";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,Code,Code_His,Name,Name_His,Spec,Manufacturer,Price,WarehouseAmount,Money,DeliveryCode,DeliveryDetailCode,SupplierCode,SupplierName,SupplierCode_His,SupplierName_His,DeliveryTime,"
            + "Spec_His,Manufacturer_His,RegistrationCode,RegistrationCode_His,Form,Form_His,UnitMinForm"
            + ",BatchCode,MakeDate,ExpiredDate,Unit,Unit_His,UnitRatio,WarehouseRatio,Price_His,Price_Warehouse,Amount,PurchaseAmount,InvoiceNo,InvoiceDate,Salesman"
            + ",WarehouseCode,WarehouseName,PurchaseOrderCode,PurchaseOrderDetailCode,PurchaseTime,StockInId,InvoiceCheckStatus,SupervisionCodeStatus,ReciveStatus,TwoTicksStatus,OperateUserName";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            // 与SqlField同
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "0,80,80,160,160,120,140,80,80,80"
            +",80,80,80,120,80,120,80,80,160,80"
            +",80,60,60,60,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);
        }
        private void ShowDeliverDetail(DataGridViewRow dgvr)
        {
            txtDeliveryCode.Text = dgvr.Cells["DeliveryCode"].Value.ToString();
            
            txtSupplierName.Text = dgvr.Cells["SupplierName"].Value.ToString();
            
            txtDeliveryTime.Text = dgvr.Cells["DeliveryTime"].Value.ToString();
            txtInvoiceNoX.Text = dgvr.Cells["InvoiceNo"].Value.ToString();
            txtInvoiceDate.Text = dgvr.Cells["InvoiceDate"].Value.ToString();
            txtBillMoney.Text= dgvr.Cells["Money"].Value.ToString();
            txtPurchaseAmount.Text= dgvr.Cells["PurchaseAmount"].Value.ToString();
            txtCode0.Text = dgvr.Cells["Code"].Value.ToString(); //药品名称
            txtUnit0.Text = dgvr.Cells["Unit"].Value.ToString();
            //txtUnitMinForm0.Text = dgvr.Cells["UnitMinForm"].Value.ToString();
            txtBatchCode.Text= dgvr.Cells["BatchCode"].Value.ToString();
            txtMakeDate.Text = dgvr.Cells["MakeDate"].Value.ToString();
            txtExpiredDate.Text = dgvr.Cells["ExpiredDate"].Value.ToString();
            txtName0.Text = dgvr.Cells["Name"].Value.ToString();
            txtAmount.Text = dgvr.Cells["Amount"].Value.ToString();
            //txtWarehouseName.Text = dgvr.Cells["WarehouseName"].Value.ToString();
            txtPrice0.Text = dgvr.Cells["Price"].Value.ToString();
            txtForm0.Text = dgvr.Cells["UnitRatio"].Value.ToString();
            //txtApproveCode0.Text = dgvr.Cells["RegistrationCode"].Value.ToString();
            txtSpec0.Text = dgvr.Cells["Spec"].Value.ToString();
            txtMaker0.Text = dgvr.Cells["Manufacturer"].Value.ToString();
            //txtBatchCode.Text = dgvr.Cells["BatchCode"].Value.ToString();
            //txtMakeDate.Text = dgvr.Cells["MakeDate"].Value.ToString();
            //txtExpiredDate.Text = dgvr.Cells["ExpiredDate"].Value.ToString();
            txtCode1.Text = dgvr.Cells["Code_His"].Value.ToString();
            txtUnit1.Text = dgvr.Cells["Unit_His"].Value.ToString();
            txtPrice1.Text = dgvr.Cells["Price_His"].Value.ToString();
            txtName1.Text = dgvr.Cells["Name_His"].Value.ToString();
            //txtForm1.Text = dgvr.Cells["Name_His"].Value.ToString();
            //txtApproveCode1.Text = dgvr.Cells["RegistrationCode_His"].Value.ToString();
            txtSpec1.Text = dgvr.Cells["Spec_His"].Value.ToString();
            txtMaker1.Text = dgvr.Cells["Manufacturer_His"].Value.ToString();
            txtInvoiceCheckStatus.Text = dgvr.Cells["InvoiceCheckStatus"].Value.ToString();
            txtSupervisionCodeStatus.Text = dgvr.Cells["SupervisionCodeStatus"].Value.ToString();
            txtReciveStatus.Text = dgvr.Cells["ReciveStatus"].Value.ToString();
            txtTwoTicksStatus.Text = dgvr.Cells["TwoTicksStatus"].Value.ToString();
            
        }
        /// <summary>
        /// 初始化配企信息
        /// </summary>
        private void _initCustomer()
        {
            // 01 取配企信息
            string strSql = "";
            strSql = "select Supplier from(select '未对码|' as Supplier,1000 as ShowOrder union (select Name + '|' + Code as Supplier,isnull(ShowOrder,0) as ShowOrder from T_Base_SupplierCodeCheck where CheckCodeStatus = 1 and InstitutionCode = '{0}'))A order by ShowOrder desc";
            strSql = string.Format(strSql, AppInfo.m_UserInfo.m_strDeptCode);
            DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                FunctionComm._setInfoToCbb_Dt(cbbCustomer, dt);
                // 02 保存临时数据(过滤用)
                m_cbbData = new string[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    m_cbbData[i] = dt.Rows[i][0].ToString();
                }
            }
        }
        private void _iniSmr()
        {
            // 01 取配企信息 where InstitutionCode = '{0}'
            string strSql = "";
            strSql = "select F_RealName + '|' + F_Account as Smr from lr_base_user order by F_CreateDate desc";
            //strSql = string.Format(strSql, AppInfo.m_UserInfo.m_strDeptCode);
            DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                FunctionComm._setInfoToCbb_Dt(cbbsmr, dt);
                // 02 保存临时数据(过滤用)
                m_cbbData1 = new string[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    m_cbbData1[i] = dt.Rows[i][0].ToString();
                }
            }
        }

        /// <summary>
        /// 取查询条件
        /// </summary>
        private Boolean _getQueryWhere(ref string strWhere)
        {
            Boolean bResult = false;
            string strTemp = "";
            
            // 01 取客户名称
            if (cbCustomer.Checked && cbbCustomer.SelectedIndex > -1)
            {
                strTemp = cbbCustomer.Text.Split('|')[1].Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(SupplierCode_His = '{0}')", strTemp);
                }
            }
            // 02 取配送日期
            if (cbDate.Checked)
            {
                if (dtpDateBegin.Value.ToString("yyyy-MM-dd").CompareTo(dtpDateEnd.Value.ToString("yyyy-MM-dd")) > 0)
                {
                    CommFun._messageBoxShow(string.Format("起始日期大于终止日期！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return bResult;
                }
                else
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(DeliveryTime >= '{0}' and DeliveryTime <= '{1}')", dtpDateBegin.Value.ToString("yyyy-MM-dd"), dtpDateEnd.Value.AddDays(1).ToString("yyyy-MM-dd"));
                }
            }
            if (cbsmr.Checked)
            {
                strTemp = cbbsmr.Text.Split('|')[1].Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(OperateUserId ='{0}')", strTemp);
                }
            }
            // 03 取发票日期
            //if (cbInvoiceDate.Checked)
            //{
            //if (dtpInvoiceDateBegin.Value.ToString("yyyy-MM-dd").CompareTo(dtpInvoiceDateEnd.Value.ToString("yyyy-MM-dd")) > 0)
            //{
            //CommFun._messageBoxShow(string.Format("起始日期大于终止日期！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //return false;
            //}
            //else
            //{
            //strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceDate >= '{0}' and InvoiceDate <= '{1}')", dtpInvoiceDateBegin.Value.ToString("yyyy-MM-dd"), dtpInvoiceDateEnd.Value.ToString("yyyy-MM-dd"));
            //}
            //}
            // 04 商品编号
            if (cbGoodsCode.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Code like '%{0}%' or Code_His like '%{0}%')", txtGoodsCode.Text.Trim(), txtGoodsCode.Text.Trim());
            }
            // 05 商品名称
            if (cbGoodsName.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Name like '%{0}%')", txtGoodsName.Text.Trim());
            }
            // 06 发票号
            if (cbInvoiceNo.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceNo like '%{0}%')", txtInvoiceNo.Text.Trim());
            }
            //// 07 物流单号
            //if (cbStockOutCode.Checked)
            //{
            //    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(DZJGMLBM like '%{0}%')", txtStockOutCode.Text.Trim());
            //}            
            // 08 入库库房
            //if (cbWarehouse.Checked)
            //{
                //strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(WarehouseName,'') = '' or WarehouseName = '{0}')", cbbWarehouse.Text.Split('|')[0].Trim());
            //}
            //09 发票核对
            if (cbInvoiceCheck.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(InvoiceCheckStatus,'') = '' or InvoiceCheckStatus = '{0}')", cbbInvoiceCheck.Text.Trim());
            }
            //10 是否收货
            if (cbRecive.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(ReciveStatus,'') = '' or ReciveStatus = '{0}')", cbbRecive.Text.Trim());
            }
            //11 溯源状态
            if (cbSupervision.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(SupervisionCodeStatus,'') = '' or SupervisionCodeStatus = '{0}')", cbbSupervision.Text.Trim());
            }
            //12 两票凭证状态
            if (cbTwoTicks.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(TwoTicksStatus,'') = '' or TwoTicksStatus = '{0}')", cbbTwoTicks.Text.Trim());
            }
            bResult = true;
            return bResult;
        }
        
        /// <summary>
        /// 信息查询
        /// </summary>
        private void _query()
        {
            if (m_dt != null)
            {
                m_dt.Dispose();
            }
            // 00 取条件:有参数时按参数来取数据
            string strWhere = "";
            strWhere = " InstitutionCode='{0}' and isnull(StockInStatus,0) = 0";
            strWhere = string.Format(strWhere, AppInfo.m_UserInfo.m_strDeptCode);
            if (_getQueryWhere(ref strWhere))
            {
                if (!strWhere.Equals(""))
                {
                    strWhere = string.Format(" where {0}", strWhere);
                }
                // 02 取数据
                string strFieldTemp = AppConfig.m_dictFieldSql[this.Name];
                //// 选中客户时只显示该客户信息
                //if (cbCustomer.Checked) {
                //    strFieldTemp = strFieldTemp.Replace("CustomerCode",string.Format("'{0}' as CustomerCode",cbbCustomer.Text.Split('|').Length > 1?cbbCustomer.Text.Split('|')[1].Trim():""));
                //    strFieldTemp = strFieldTemp.Replace("CustomerName",string.Format("'{0}' as CustomerName",cbbCustomer.Text.Split('|')[0].Trim()));
                //}
                string strSql = string.Format("SELECT {0} FROM V_DeliveryDetail {{0}} order by InvoiceNo", strFieldTemp);
                strSql = string.Format(strSql, strWhere);
                m_dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);

                m_strSql = strSql;  // 更新数据用
            }
            // 03 显示数据
            DataTable dt = null;
            if (m_dt != null)
            {
                dt = m_dt.Copy();
            }
            _showData(dt);
        }
        private void _queryByInvoiceNo(string _invoiceNo)
        {
            try
            {
                string strWhere = "";
                strWhere = "where InstitutionCode='{0}' and isnull(StockInStatus,0) = 0";
                strWhere = string.Format(strWhere, AppInfo.m_UserInfo.m_strDeptCode);
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceNo like '%{0}%')", _invoiceNo);
                string strFieldTemp = AppConfig.m_dictFieldSql[this.Name];
                string strSql = string.Format("SELECT {0} FROM V_DeliveryDetail {{0}} order by InvoiceNo", strFieldTemp);
                strSql = string.Format(strSql, strWhere);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);

                m_strSql = strSql;  // 更新数据用
                // 03 显示数据

                if (dt.Rows.Count > 0)
                {
                    if (m_dt == null)
                        m_dt = dt.Clone();
                    foreach (DataRow dr in dt.Rows)
                    {
                        m_dt.Rows.Add(dr.ItemArray);
                    }
                    dt = m_dt.Copy();
                    _showData(dt);
                }
                else
                {
                    CommFun._messageBoxShow("该发票号码对应运单数据未找到！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtInvoiceNo.Focus();
                }
            }
            catch(Exception e)
            {
                CommDll.DBLog._writeLog(e);
            }
        }
        /// <summary>
        /// 信息过滤
        /// </summary>
        private void _query0()
        {
            // 00 数据初始化
            DataTable dt = m_dt.Copy();
            DataView dv = dt.DefaultView;
            dv.RowFilter = "1<>1";  // 默认无数据
            // 01 取条件:有参数时按参数来取数据
            string strWhere = "";
            if (_getQueryWhere(ref strWhere))
            {
                dv.RowFilter = strWhere;
            }  
            // 02显示数据
            _showData(dv.ToTable());
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showData(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                // 0101 调整字段顺序
                CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name]);
                // 0102 显示数据
                CommFun._showDataGridView0(dataGridViewX1, dt, AppConfig.m_dictFieldWidth[this.Name], AppConfig.m_dictFieldName[this.Name], true,false); 
                // 0103 特殊行处理
                _showSpecRow();
            }
            else {
                // 清除数据
                DataTable dtTemp = (DataTable)dataGridViewX1.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }      
            }
            _GetTotalInfo();// lblRecord.Text = string.Format("提示:共有数据信息 {0} 项", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void _init()
        {
            // 01 dataGridViewX1设为不可编辑
            dataGridViewX1.ReadOnly = true;
            dataGridViewX1.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            // 02 初始化日期
            dtpDateBegin.Format = DateTimePickerFormat.Custom;
            dtpDateBegin.CustomFormat = "yyyy-MM-dd";
            dtpDateEnd.Format = dtpDateBegin.Format;
            dtpDateEnd.CustomFormat = dtpDateBegin.CustomFormat;
            //dtpInvoiceDateBegin.Format = dtpDateBegin.Format;
            //dtpInvoiceDateBegin.CustomFormat = dtpDateBegin.CustomFormat;
            //dtpInvoiceDateEnd.Format = dtpDateBegin.Format;
            //dtpInvoiceDateEnd.CustomFormat = dtpDateBegin.CustomFormat;

            dtpDateEnd.Value = DateTime.Now;
            dtpDateBegin.Value = dtpDateEnd.Value.AddDays(AppConfig.m_nDateBeforeDistribution * -1);
            //dtpInvoiceDateEnd.Value = DateTime.Now;
            //dtpInvoiceDateBegin.Value = dtpInvoiceDateEnd.Value.AddDays(AppConfig.m_nDateBeforeInvoice * -1);
            // 03 初始化配企
            _initCustomer();
            _iniSmr();
            // 04 取库房信息
            //FunctionComm._setInfoToCbb_Dt(cbbWarehouse, AppInfo.m_dtWarehouse);
            FunctionComm._setInfoToCbb_Dt(cbbWarehouseIn, AppInfo.m_dtWarehouse);
            // 05 DataGridView
            _initDgvTitle();
            cbbRecive.SelectedIndex = 1;
        }

        /// <summary>
        /// 设置全选或全不选
        /// </summary>
        /// <param name="nKind">1：全选 0：全不选</param>
        private void _SelectAll(int nKind)
        {
            if (dataGridViewX1.Rows.Count > 0)
            {
                this.dataGridViewX1.CurrentCell = null; // 设置当前列，因为如当前列在选择列时，会出现不能设置数据情况
                foreach (DataGridViewRow row in dataGridViewX1.Rows)
                {
                    row.Cells[m_nFieldSelectedOrder].Value = nKind;
                }
            }
        }

        /// <summary>
        /// 取选中的数据项信息,倒排方式,当nKind==0时,需去除未选数据
        /// </summary>
        /// <param name="nKind">0:去除未选项 1:取已先数据编号</param>
        private string _GetSelectedInfo(int nKind = 0)
        {
            // 01 去除未选项
            string strResult = "";
            string strID = "";
            for (int i = dataGridViewX1.Rows.Count - 1; i >= 0; i--)
            {
                strID = dataGridViewX1.Rows[i].Cells["IsSelected"].Value.ToString();
                if (!strID.Equals("1"))
                {
                    if (nKind == 0)
                    {
                        //0:去除未选项
                        dataGridViewX1.Rows.RemoveAt(i);
                    }
                }
                else
                {
                    strResult += (strResult.Equals("") ? "" : ",") + dataGridViewX1.Rows[i].Cells["ID"].Value.ToString();
                }
            }
            // 显示行号
            CommFun._formatHeaderCell(dataGridViewX1);
            _GetTotalInfo();// lblRecord.Text = string.Format("提示:共有数据信息 {0} 项", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count);
            return strResult;
        }

        /// <summary>
        /// 取汇总信息
        /// </summary>
        private void _GetTotalInfo()
        {
            double dTotal = 0;
            for (int i = dataGridViewX1.Rows.Count - 1; i >= 0; i--)
            {
                dTotal += FunctionComm._strToFloat(dataGridViewX1.Rows[i].Cells["Money"].Value.ToString());
            }
            lblRecord.Text = string.Format("提示:共有数据信息 {0} 项,合计:{1}元", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count, dTotal);
        } 

        /// <summary>
        /// 特殊行处理
        /// </summary>
        private void _showSpecRow()
        {
            if (dataGridViewX1.Columns.Contains("RegistrationCode") && dataGridViewX1.Columns.Contains("RegistrationCode_His"))
            {
                foreach (DataGridViewRow dr in dataGridViewX1.Rows)
                {
                    // 未对码蓝色
                    if (dr.Cells["Code_His"].Value.ToString().ToLower().Length < 1)
                    {
                        foreach (DataGridViewCell dc in dr.Cells)
                        {
                            dc.Style.ForeColor = Color.Blue;
                        }
                        continue;
                    }
                    else
                    {
                        if (dr.Cells["Code_His"].Style.ForeColor == Color.Blue)
                        {
                            foreach (DataGridViewCell dc in dr.Cells)
                            {
                                dc.Style.ForeColor = Color.Black;
                            }
                        }
                    }

                    // 批准文号不同显示红色
                    if (!dr.Cells["RegistrationCode"].Value.ToString().ToLower().Equals(dr.Cells["RegistrationCode_His"].Value.ToString().ToLower()))
                    {
                        dr.Cells["RegistrationCode"].Style.ForeColor = Color.Red;
                    }
                    else {
                        if (dr.Cells["RegistrationCode"].Style.ForeColor == Color.Red)
                        {
                            dr.Cells["RegistrationCode"].Style.ForeColor = Color.Black;
                        }
                    }

                    // 单价不同显示粉色
                    if (FunctionComm._strToFloat(dr.Cells["Price_Warehouse"].Value.ToString().ToLower()) != FunctionComm._strToFloat(dr.Cells["Price_His"].Value.ToString().ToLower()))
                    {
                        foreach (DataGridViewCell dc in dr.Cells)
                        {
                            dc.Style.ForeColor = Color.Red;
                        }
                    }
                    else {
                        if (dr.Cells["Price"].Style.ForeColor == Color.Red)
                        {
                            foreach (DataGridViewCell dc in dr.Cells)
                            {
                                dc.Style.ForeColor = Color.Black;
                            }
                        }                        
                    }
                }
            }
        }
        #endregion

        #region 03.系统事件方法

        private void frm_Load(object sender, EventArgs e)
        {
            _init();
        }

        private void cbbCustomer_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 重绘使可以调整行距
            CommFun._cbbDrawItem(sender, e);
        }

        private void cbbCustomer_TextUpdate(object sender, EventArgs e)
        {
            // 数据过滤
            CommFun._cbbFilter((ComboBox)sender, m_cbbData);
            Cursor = Cursors.Default;
        }

        private void cbCustomer_CheckedChanged(object sender, EventArgs e)
        {
            // 过滤条件变化进行数据过滤
            if (m_dt == null || m_dt.Rows.Count < 1)
            {
                return;
            }
            // 按数据类来处理
            Boolean bRefresh = true;
            Control control = (Control)sender;
            switch (control.Name)
            {
                case "cbbCustomer":
                    bRefresh = cbCustomer.Checked;
                    break;
                case "txtGoodsCode":
                    bRefresh = cbGoodsCode.Checked;
                    break;
                case "txtGoodsName":
                    bRefresh = cbGoodsName.Checked;
                    break;
                //case "txtStockOutCode":
                //    bRefresh = cbStockOutCode.Checked;
                //    break;
                case "txtInvoiceNo":
                    bRefresh = cbInvoiceNo.Checked;                    
                    break;
                case "dtpDateBegin":
                case "dtpDateEnd":
                    bRefresh = cbDate.Checked;
                    break;
                //case "dtpInvoiceDateBegin":
                case "cbbsmr":
                    bRefresh = cbsmr.Checked;
                    break;
            }
            if (bRefresh)
            {
                //_query0();
            }
        }
        private void _checkInvoiceNo()
        {
            string _invoiceNo = txtInvoiceNo.Text.Trim();
            if (!string.IsNullOrEmpty(_invoiceNo))
            {                
                _invoiceNo.Replace("，", ",");
                if (_invoiceNo.Contains(","))
                {
                    string[] splittmp = _invoiceNo.Split(',');
                    if (splittmp.Length >= 4)
                    {
                        txtInvoiceNo.Text = splittmp[3];
                        _CheckInvoiceStatus(splittmp[3]);
                    }
                }
                else
                {
                    _CheckInvoiceStatus(_invoiceNo);
                }
                txtInvoiceNo.SelectAll();
            }
        }
        private void _CheckInvoiceStatus(string _invoiceNo)
        {
            string strSql = "";
            // 更新数据发票核验状态
            strSql = string.Format("Update T_DeliveryDetail set InvoiceCheckStatus='核对' where InvoiceNo = '{0}'", _invoiceNo);
            int nResult = DbHelper.DBAccess[0]._execSql(strSql);
            _queryByInvoiceNo(_invoiceNo);
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            // 数据查询
            _query();           
        }

        private void btnSelected_Click(object sender, EventArgs e)
        {
            // 显示已选择项
            _GetSelectedInfo();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            // 数据过出
            if (dataGridViewX1 != null && dataGridViewX1.Rows.Count > 0)
            {
                CommFun._ExportExcel("", dataGridViewX1);
            }
        }

        private void btnStockIn_Click(object sender, EventArgs e)
        {
            // 00 数据校验
            if (!(cbCustomer.Checked && cbbCustomer.SelectedIndex > -1))
            {
                CommFun._messageBoxShow("请先确定要入库的配企名称!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (cbbWarehouseIn.SelectedIndex < 0) {
                CommFun._messageBoxShow("请先确定入库库房名称!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            // 数据入库
            // 01 取选择的数据项
            string strInfoID = _GetSelectedInfo(1);
            if (strInfoID.Equals(""))
            {
                CommFun._messageBoxShow("请先确定要入库的配送数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult result = CommFun._messageBoxShow(string.Format("是否确定当前配送数据入库到库房【{0}】?", cbbWarehouseIn.Text), "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes)
            {
                return;
            }
            // 03 入库处理
            bool bOK = true;
            DataTable dt = (DataTable)dataGridViewX1.DataSource;
            DataView dv = dt.DefaultView;
            dv.RowFilter = string.Format("ID in ({0})", strInfoID);
            DataTable dt1 = dv.ToTable(true);
            _GetTotalInfo();// lblRecord.Text = string.Format("提示:共有数据信息 {0} 项", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count);
            // 判断是否编码
            foreach (DataRow dr in dt1.Rows)
            {
                if (dr["SupplierName_His"].ToString().Equals(""))
                {
                    CommFun._messageBoxShow("有配企数据对未码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bOK = false;
                    break;
                }
                if (dr["Name_His"].ToString().Equals(""))
                {
                    CommFun._messageBoxShow("有药品数据对未码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bOK = false;
                    break;
                }
                if(dr["ReciveStatus"].ToString().Equals("未收")|| dr["ReciveStatus"].ToString().Equals("拒收"))
                {
                    DialogResult dre= CommFun._messageBoxShow("有配送货物未收货或拒收,是否确定要入库!", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if(dre==DialogResult.Cancel)
                    {
                        bOK = false;
                        break;
                    }
                }
            }
            if (!bOK)
            {
                return;
            }
            //调用HIS接口-配企出库单转HIS入库单制单
            string errmsg = "";
            string strSql = "";
            string strStockInCode = "";
            try
            {
                string[] InfoIDArr = strInfoID.Split(',');
                int false_count = 0;
                for (int i = 0; i < InfoIDArr.Length; i++)
                {
                    strSql = "exec P_MakeStockIn '{0}','{1}','{2}','{3}','{4}'";
                    strSql = string.Format(strSql, InfoIDArr[i], cbbWarehouseIn.Text, cbbCustomer.Text.Split('|')[1].Trim(), cbbCustomer.Text.Split('|')[0].Trim(), AppInfo.m_UserInfo.m_strCode);
                    DataTable dt0 = DbHelper.DBAccess[0]._openSql_Dt(strSql);

                    if (dt0 != null && dt.Rows.Count > 0)
                    {
                        strStockInCode = dt0.Rows[0]["StockInCode"].ToString();
                    }
                    bOK = !strStockInCode.Equals("");
                    if (bOK)
                    {
                        // 04 提交到HIS入库
                        bool isok = His_DrugTracePurchaseInstore_new(strStockInCode, ref errmsg);
                        // 05 更新数据
                        if (isok)
                        {                            
                            foreach (DataRow dr in ((DataTable)dataGridViewX1.DataSource).Rows)
                            {
                                if (dr.RowState != DataRowState.Deleted && ((System.Collections.IList)InfoIDArr).Contains(dr["ID"].ToString()))
                                {
                                    dr["StockInID"] = strStockInCode;
                                }
                            }
                        }
                        else
                        {
                            false_count++;
                            //把数据还原到之前的状态
                            strSql = "delete from T_StockIn where StockInID='" + strStockInCode + "'";
                            DbHelper.DBAccess[0]._execSql(strSql);
                            strSql = "update T_DeliveryDetail set StockInStatus=0,StockInID='',StockInDetailID='' where StockInID='" + strStockInCode + "'";
                            DbHelper.DBAccess[0]._execSql(strSql);
                            CommFun._messageBoxShow(string.Format("本次数据入库失败！" + errmsg + "", ""), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        false_count++;
                        CommFun._messageBoxShow(string.Format("本次数据入库失败！", ""), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                int successcount = InfoIDArr.Length - false_count;
                CommFun._messageBoxShow(string.Format("数据入库完成,共入库数据{0}条！", strInfoID.Equals("") ? "0" : successcount.ToString()), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                if (strStockInCode != "")
                {
                    //把数据还原到之前的状态
                    strSql = "delete from T_StockIn where StockInID='" + strStockInCode + "'";
                    DbHelper.DBAccess[0]._execSql(strSql);
                    strSql = "update T_DeliveryDetail set StockInStatus=0,StockInID='',StockInDetailID='' where StockInID='" + strStockInCode + "'";
                    DbHelper.DBAccess[0]._execSql(strSql);
                }
                CommDll.DBLog._writeLog(ex);
                CommFun._messageBoxShow(string.Format("本次数据入库失败！" + ex.Message, ""), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private bool His_DrugTracePurchaseInstore_new(string stocodeid, ref string errmsg)
        {
            bool isok = false;
            string url = DbHelper._getHisAddress();// + "DrugTracePurchaseInstore";
            if(url.Equals("")||url.Equals("http://"))
            {
                return true;
            }
            string sql = "select SupplierCode supplierCode,SupplierName SupplierName,WarehouseCode WarehouseCode,WarehouseName WarehouseName," +
"StockInDetailID Xno, Code DrugCode,Name as Name,Spec packSpec, Manufacturer, Unit, Unit as SpecUnit,1 SpecRatio," +
"BatchCode BatchNumber,convert(varchar(10),ExpiredDate,120) as ExpiredDate, Amount, Price, InvoiceNo, convert(varchar(10),InvoiceDate,120) InvoiceDate, Money,OperatorName,convert(varchar(20),StockInTime,120) CreateTime," +
"convert(varchar(10),MakeDate,120) as MakeDate,RegistrationCode from T_StockIn where stockInId='" + stocodeid + "'";
            DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(sql);
            if (dt.Rows.Count > 0)
            {
                string body = "{\"drugTracePurchaseInstores\": " + JsonConvert.SerializeObject(dt) + "}";
                string resCode = HisInterFace.Post(url, body);
                string files = AppDomain.CurrentDomain.BaseDirectory + "\\DBlog\\" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
                FileSystemObject.Create(files, FsoMethod.File);
                FileSystemObject.WriteFile(files, "url:" + url + "\r\n");
                FileSystemObject.WriteFile(files, "para:" + body + "\r\n", true);
                FileSystemObject.WriteFile(files, "result:" + resCode + "\r\n", true);
                JObject jo = (JObject)JsonConvert.DeserializeObject(resCode);
                bool isTrue = false;
                bool.TryParse(jo["Successed"].ToString(), out isTrue);

                if (isTrue)
                {
                    isok = true;
                    string code = jo["Data"]["His_code"].ToString();
                    string strSql = "update T_DeliveryDetail set StockInCode_His='{0}' where stockInId='{1}'";
                    strSql = string.Format(strSql, code, stocodeid);
                    int nResult = DbHelper.DBAccess[0]._execSql(strSql);
                }
                else
                {
                    errmsg = jo["TradeMessage"].ToString();
                }

            }
            return isok;
        }
        private bool His_DrugTracePurchaseInstore(DataTable dt, ref string errmsg)
        {
            bool isok = false;
            string url = DbHelper._getHisAddress();// + "DrugTracePurchaseInstore";
            if (!url.Equals("") && !url.Equals("http://"))
            {
                url+= "DrugTracePurchaseInstore";
                string strJson = "{\"drugTracePurchaseInstores\":[";
                string jsonlist = "";
                int i = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    if (i > 0)
                    {
                        jsonlist = jsonlist + ",";

                    }
                    jsonlist = jsonlist + "{\"supplierCode\":\"" + dr["SupplierCode_His"].ToString() + "\",\"SupplierName\":\"" + dr["SupplierName_His"].ToString() + "\",\"WarehouseCode\":\"" + cbbWarehouseIn.Text.Substring(cbbWarehouseIn.Text.IndexOf("|") + 1)
                        + "\",\"WarehouseName\":\"" + cbbWarehouseIn.Text.Substring(0, cbbWarehouseIn.Text.IndexOf("|")) + "\",\"Xno\":\"" + dr["DeliveryDetailCode"].ToString() + "\",\"DrugCode\":\"" + dr["Code_His"].ToString()
                        + "\",\"Name\":\"" + dr["Name_His"].ToString() + "\",\"packSpec\":\"" + dr["Spec_His"].ToString() + "\",\"Manufacturer\":\"" + dr["Manufacturer_His"].ToString() + "\",\"Unit\":\"" + dr["Unit"].ToString()
                        + "\",\"SpecUnit\":\"" + dr["Unit"].ToString() + "\",\"SpecRatio\":\"1\",\"BatchNumber\":\"" + dr["BatchCode"].ToString() + "\",\"ExpiredDate\":\"" + Convert.ToDateTime(dr["ExpiredDate"]).ToString("yyyy-MM-dd")
                        + "\",\"Amount\":" + dr["Amount"].ToString() + ",\"Price\":" + dr["Price_His"].ToString() + ",\"InvoiceNo\":\"" + dr["InvoiceNo"].ToString() + "\",\"InvoiceDate\":\"" + Convert.ToDateTime(dr["InvoiceDate"]).ToString("yyyy-MM-dd")
                        + "\",\"Money\":" + dr["Money"].ToString() + ",\"OperatorName\":\"" + AppInfo.m_UserInfo.m_strName + "\",\"CreateTime\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}";

                }
                try
                {
                    strJson = strJson + jsonlist + "]}";
                    string resCode = HisInterFace.Post(url, strJson);
                    JObject jo = (JObject)JsonConvert.DeserializeObject(resCode);
                    bool isTrue = false;
                    bool.TryParse(jo["Successed"].ToString(), out isTrue);
                    string files = AppDomain.CurrentDomain.BaseDirectory + "\\DBlog\\" + DateTime.Now.ToString("MMddHHmmssfff") + ".txt";
                    FileSystemObject.Create(files, FsoMethod.File);
                    FileSystemObject.WriteFile(files, "url:" + url + "\r\n");
                    FileSystemObject.WriteFile(files, "para:" + strJson + "\r\n", true);
                    FileSystemObject.WriteFile(files, "result:" + resCode + "\r\n", true);
                    if (isTrue)
                    {
                        isok = true;
                        string code = jo["Data"]["His_code"].ToString();
                        foreach (DataRow dr in dt.Rows)
                        {
                            string strSql = "update T_DeliveryDetail set StockInCode_His='{0}' where ID={1}";
                            strSql = string.Format(strSql, code, dr["ID"].ToString());
                            int nResult = DbHelper.DBAccess[0]._execSql(strSql);
                        }
                    }
                    else
                    {
                        errmsg = jo["TradeMessage"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    CommDll.DBLog._writeLog(ex);
                }

            }
            return isok;
        }
        #endregion

        #region GridViewX事件

        private void dataGridViewX1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 选择列标题双击操作
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];
            if (e.ColumnIndex == m_nFieldSelectedOrder)
            {
                // 判定当前全选或未选状态
                if (newColumn.HeaderText.Contains("☑"))
                {
                    newColumn.HeaderText = "□";
                    _SelectAll(0);
                }
                else
                {
                    newColumn.HeaderText = "☑";
                    _SelectAll(1);
                }
            }
            else {
                // 排序
                CommFun._dgvColumnHeaderSort(sender, e);
                _showSpecRow();
            }            
        }

        private void dataGridViewX1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 鼠标拖动多选时用:确定起始单元格
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                m_bIsSelectBegin = false;
                return;
            }
            // 只是单选框时作多项选择操作(鼠标按下不放多选)
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];
            // 判断是否可编辑列
            if (newColumn.DataPropertyName.Equals("IsSelected"))
            {
                m_bIsSelectBegin = true;
            }
            else {
                m_bIsSelectBegin = false;
            }
        }

        private void dataGridViewX1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 鼠标拖动多选时用:确定结束单元格
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                m_bIsSelectBegin = false;
                return;
            }
            // 只是单选框时作多项选择操作(鼠标按下不放多选)
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];            
            if (newColumn.DataPropertyName.Equals("IsSelected") && m_bIsSelectBegin)
            {
                foreach (DataGridViewCell item in ((DataGridView)sender).SelectedCells)
                {
                    if (item.ColumnIndex == m_nFieldSelectedOrder) {
                        if (((item.Value == null) ? "0" : item.Value.ToString()) == "1")
                        {
                            item.Value = 0;
                        }
                        else
                        {
                            item.Value = 1;
                        }
                    }
                }
            }
        }
        
        private void dataGridViewX1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string strTemp = "";
            // 单元格双击操作，对于可编辑的列进行编辑状态，否则不能进行编辑,显示详细信息
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            // 只是单选框时作多项选择操作
            DataGridView dgv = (DataGridView)sender;
            DataGridViewColumn newColumn = dgv.Columns[e.ColumnIndex];
            // 判断是否可编选择列
            if (!newColumn.DataPropertyName.Equals("IsSelected"))
            {
                // 对码的数据列
                switch (newColumn.DataPropertyName)
                {
                    case "SupplierCode_His":
                    case "SupplierName_His":
                        // 配企对码
                        frmQuery_EnterpriseCodeCheck0 frm1 = new frmQuery_EnterpriseCodeCheck0();
                        frm1.WindowState = FormWindowState.Normal;
                        frm1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;

                        ModelSupplierCodeCheck.strCode1 = dgv.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToString();
                        ModelSupplierCodeCheck.strName1 = dgv.Rows[e.RowIndex].Cells["SupplierName"].Value.ToString();
                        ModelSupplierCodeCheck.strLinkman1 = dgv.Rows[e.RowIndex].Cells["Salesman"].Value.ToString();
                        strTemp = dgv.Rows[e.RowIndex].Cells["SupplierCode_His"].Value.ToString().Trim();
                        frm1.m_dictInfo.Add("SupplierCode_His", strTemp);
                        frm1.m_dictInfo.Add("Name_His", dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString());
                        frm1.m_dictInfo.Add("Spec_His", dgv.Rows[e.RowIndex].Cells["Spec"].Value.ToString());
                        frm1.m_dictInfo.Add("Unit_His", dgv.Rows[e.RowIndex].Cells["Unit"].Value.ToString());
                        frm1.m_dictInfo.Add("Manufacturer_His", dgv.Rows[e.RowIndex].Cells["Manufacturer"].Value.ToString());
                        if (frm1.ShowDialog() == DialogResult.OK)
                        {
                            // 更新配企数据
                            _initCustomer();
                            //// 更新配企(配送数据)
                            //DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(m_strSql);
                            //Dictionary<string, string> dict = new Dictionary<string, string>();
                            //foreach (DataRow dr in dt.Rows)
                            //{
                            //    dict.Add(dr["ID"].ToString(), string.Format("{0}|{1}", dr["SupplierCode_His"].ToString(), dr["SupplierName_His"].ToString()));
                            //}
                            // 更新数据                        
                            ((DataTable)((DataGridView)sender).DataSource).Columns["SupplierCode_His"].ReadOnly = false;
                            ((DataTable)((DataGridView)sender).DataSource).Columns["SupplierName_His"].ReadOnly = false;
                            foreach (DataRow dr in ((DataTable)dgv.DataSource).Rows)
                            {
                                if (dr.RowState != DataRowState.Deleted && dr["SupplierCode"].ToString().Equals(ModelSupplierCodeCheck.strCode1))
                                {
                                    dr["SupplierCode_His"] = ModelSupplierCodeCheck.strCode0;
                                    dr["SupplierName_His"] = ModelSupplierCodeCheck.strName0;
                                }
                            }
                        }
                        break;
                    case "Code_His":
                    case "Name_His":
                        // 药品对码
                        frmQuery_MedicineCodeCheck0 frm2 = new frmQuery_MedicineCodeCheck0();
                        frm2.WindowState = FormWindowState.Normal;
                        frm2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
                        frm2.m_dgvRow = dgv.Rows[e.RowIndex];
                        // 取数据
                        frm2.m_dictInfo.Add("CodeSupplier", dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString().Trim());
                        frm2.m_dictInfo.Add("SupplierCode", dgv.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToString().Trim());
                        frm2.m_dictInfo.Add("Price", dgv.Rows[e.RowIndex].Cells["Price"].Value.ToString().Trim());
                        ((DataTable)((DataGridView)sender).DataSource).Columns["Price_His"].ReadOnly = false;
                        if (frm2.ShowDialog() == DialogResult.OK)
                        {
                            // 更新所有数据
                            DataRow dr0 = DbHelper.DBAccess[0]._openSql_Row(string.Format("select * from V_DeliveryDetail where ID = {0}", dgv.Rows[e.RowIndex].Cells["ID"].Value));
                            strTemp = "Code_His,Name_His,Spec_His,Manufacturer_His,RegistrationCode_His,Form_His,Unit_His,WarehouseRatio,Price_His,Price_Warehouse,WarehouseAmount,PurchaseAmount,WarehouseName,PurchaseOrderCode,PurchaseOrderDetailCode,PurchaseTime"; 
                            if (dr0 != null)
                            {
                                DataTable DataTable0 = (DataTable)((DataGridView)sender).DataSource;
                                foreach (string str in strTemp.Split(','))
                                {
                                    if (DataTable0.Columns.Contains(str) && DataTable0.Columns[str].ReadOnly)
                                    {
                                        DataTable0.Columns[str].ReadOnly = false;
                                    }
                                }

                                foreach (DataRow dr in DataTable0.Rows)
                                {
                                    if (dr.RowState != DataRowState.Deleted && dr["SupplierCode"].ToString().Equals(frm2.m_dictInfo["SupplierCode"]) && dr["Code"].ToString().Equals(frm2.m_dictInfo["CodeSupplier"]))
                                    {
                                        foreach (string str in strTemp.Split(','))
                                        {
                                            if (DataTable0.Columns.Contains(str) && !DataTable0.Columns[str].ReadOnly)
                                            {
                                                dr[str] = dr0[str];
                                            }
                                        }
                                    }
                                }
                            }
                            // 更新颜色
                            _showSpecRow();
                        }
                        break;
                    case "InvoiceNo":
                        // 发票设置
                        frmInvoiceSet frm = new frmInvoiceSet();
                        frm.m_dictInfo.Add("ID",dgv.Rows[e.RowIndex].Cells["ID"].Value.ToString());
                        //frm.m_dictInfo.Add("InvoiceCode", dgv.Rows[e.RowIndex].Cells["InvoiceCode"].Value.ToString());
                        frm.m_dictInfo.Add("InvoiceNo", dgv.Rows[e.RowIndex].Cells["InvoiceNo"].Value.ToString());
                        frm.m_dictInfo.Add("InvoiceDate", dgv.Rows[e.RowIndex].Cells["InvoiceDate"].Value.ToString());
                        if (frm.ShowDialog() == DialogResult.OK) {
                            //dgv.Rows[e.RowIndex].Cells["InvoiceCode"].Value = frm.m_dictInfo["InvoiceCode"];
                            dgv.Rows[e.RowIndex].Cells["InvoiceNo"].Value = frm.m_dictInfo["InvoiceNo"];
                            dgv.Rows[e.RowIndex].Cells["InvoiceDate"].Value = frm.m_dictInfo["InvoiceDate"];
                        }
                        break;
                    default:
                        frmSupervisionCode frmSC = new frmSupervisionCode();
                        frmSC.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
                        // 取数据
                        frmSC.m_dictInfo.Add("Code", dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("YBCode", "");
                        frmSC.m_dictInfo.Add("Name", dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("Spec", dgv.Rows[e.RowIndex].Cells["Spec"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("RegistrationCode", dgv.Rows[e.RowIndex].Cells["RegistrationCode"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("Manufacturer", dgv.Rows[e.RowIndex].Cells["Manufacturer"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("DeliveryCode", dgv.Rows[e.RowIndex].Cells["DeliveryCode"].Value.ToString().Trim());
                        frmSC.m_dictInfo.Add("DeliveryDetailCode", dgv.Rows[e.RowIndex].Cells["DeliveryDetailCode"].Value.ToString().Trim());
                        frmSC.ShowDialog();
                        break;
                }
            }
        }
 
        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender,e);

        }

        private void dataGridViewX1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 右键双击设置标题信息 
            if (e.Button == MouseButtons.Right)
            {
                frmDataShowSetup frm = new frmDataShowSetup();
                frm.m_strInfoKind = this.Name;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (frm.m_bIsSaveWidth)
                    {
                        // 保存宽度
                        AppConfig._saveDgvWidth(dataGridViewX1, frm.m_strInfoKind, true);
                        CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        // 刷新数据
                        if (dataGridViewX1.Rows.Count > 0)
                        {
                            btnQuery_Click(null, null);
                        }
                    }
                }
            }
        }
        #endregion

        private void dataGridViewX1_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dataGridViewX1.SelectedRows.Count > 0)
            {
                // 获取当前选中的行
                DataGridViewRow selectedRow = this.dataGridViewX1.SelectedRows[0];
                //显示该行数据到右侧详情
                ShowDeliverDetail(selectedRow);
            }
        }

        private void dataGridViewX1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //DataGridView dgv = (DataGridView)sender;
            //if (dgv.RowCount > 0)
            //{
                //DataGridViewRow selectedRow = dgv.se.Rows[e.RowIndex]；
                //显示该行数据到右侧详情
                //ShowDeliverDetail(selectedRow);
           // } 
        }

        
        private void txtInvoiceNo_KeyDown_1(object sender, KeyEventArgs e)
        {
            //txtGoodsName.Text += e.KeyCode;
            if (e.KeyCode == Keys.Enter)
            {
                _checkInvoiceNo();
            }
        }

        private void txtInvoiceNo_TextChanged(object sender, EventArgs e)
        {
            //_checkInvoiceNo();
        }

        private void cbbsmr_TextUpdate(object sender, EventArgs e)
        {
            // 数据过滤
            CommFun._cbbFilter((ComboBox)sender, m_cbbData1);
            Cursor = Cursors.Default;
        }

        private void cbbsmr_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 重绘使可以调整行距
            CommFun._cbbDrawItem(sender, e);
        }
    }
}